<?php

/**
 * Description of JsonList
 *
 * @author a.novikov
 */
abstract class JsonList {
	/**
	 * Create array for transfer through Json from array of objects which implements IJsonElementProvider
	 *
	 * @param array
	 * @param string $type
	 * @return array
	 * @throws Exception
	 */
	public static function fromProviderList($list, $type = null) {
		$jsonArray = array();
		
		foreach ($list as $interface) {
			self::addElementByInterface($jsonArray, $interface, $type);
		}

		return $jsonArray;
	}

	public static function addElementByInterface(&$jsonArray, $interface, $type = null) {
		if (!$interface instanceof IJsonElementProvider) {
			throw new Exception('Interface IJsonElementProvider not implemented');
		}

		$key = null;
		$element = $interface->getJsonElement($type, $key);
		if($element !== null) {
			self::addElement($jsonArray, $element, $key);
		}
	}

	public static function addElement(&$jsonArray, $element, $key = null) {
		if ($key === null) {
			$jsonArray[] = $element;
		}
		else {
			$jsonArray[$key] = $element;
		}
	}
}